package com.lineage.server.timecontroller.event;

import com.lineage.data.event.GamblingSet;
import com.lineage.data.event.gambling.Gambling;
import com.lineage.data.event.gambling.GamblingNpc;
import com.lineage.server.datatables.lock.GamblingReading;
import com.lineage.server.model.Instance.L1DoorInstance;
import com.lineage.server.model.Instance.L1GamInstance;
import com.lineage.server.model.Instance.L1GamblingInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.L1Object;
import com.lineage.server.serverpackets.S_NpcChat;
import com.lineage.server.serverpackets.S_NpcChatShouting;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1Gambling;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.timecontroller.server.ServerRestartTimer;
import com.lineage.server.world.World;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class GamblingTime extends TimerTask {
  private static final Log _log = LogFactory.getLog(GamblingTime.class);
  
  private static Gambling _gambling;
  
  private static double rate = 0.0D;
  
  private static boolean _issystem = true;
  
  private static boolean _isStart = false;
  
  private static int _gamblingNo = 100;
  
  private static Random _random = new Random();
  
  private ScheduledFuture<?> _timer;
  
  private static final String[] _msg = new String[] { 
      "刚刚喝到的是绿水吗?等等跑就知道~^^~", "隔壁跑道听说昨天踩到钉子.....", "买我啦!!看我的脸就知道我赢!!", "快点跑完我也想去打一下副本~~", 
      "你在看我吗??你可以在靠近一点...", "飞龙都不一定跑赢我!看我强壮的鸡腿!", "那个谁谁谁!!等等不要跑超过我黑...", "有没骑士在场阿?给瓶勇水喝喝~~", "地球是很危险的...", 
      "谁给我来一下祝福!加持!加持~", 
      "咦~~有一个参赛者是传说中的跑道之王...", "没事!没事!!哥只是个传说~~", "隔壁的~你刚刚喝什么?你是不是作弊??", "肚子好饿...没吃饭能赢吗??", 
      "哇靠~~今天感觉精力充沛耶!!", "隔壁的!!你控制一下不要一直放屁!!", "嗯......嗯......其他几个是憋三,我会赢....", "我刚刚好像喝多了...头还在晕...", 
      "昨晚的妞真正丫，喝绿水算三小。", "肚子饿死了，跑不动了。", 
      "输赢都行啦，娱乐而已。", "小赌怡情，大赌伤身。", "我要放点水。经常赢都有点不好意思了。", 
      "【强化勇气的药水】是干嘛的？我这有一罐。", "昨晚被吵死了，现在都觉得好累。", "阿干....不要看我啦!!会影响我心情!!", "说什么呢~~你们不想我赢阿!!!", 
      "小赌可以养家活口!!大赌可以兴邦建国!!", "赌是不好的....不赌是万万不行的...." };
  
  public void start() {
    _gamblingNo = GamblingReading.get().maxId();
    int timeMillis = GamblingSet.GAMADENATIME * 60 * 1000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, timeMillis, timeMillis);
  }
  
  public static int get_gamblingNo() {
    return _gamblingNo;
  }
  
  public static Gambling get_gambling() {
    return _gambling;
  }
  
  public static boolean isStart() {
    return _isStart;
  }
  
  public static void set_status(boolean b) {
    _issystem = b;
  }
  
  public void run() {
    try {
      if (!_issystem ) {
    	  return;
      }
      if ( _gambling != null) {
		return;
      }
      if (ServerRestartTimer.isRtartTime()) {
		return;
      }
      
        doorOpen(false);
        long previous = 0L;
        final Iterator<L1PcInstance> iter = World.get().getAllPlayers().iterator();
        while (iter.hasNext()) {
          L1PcInstance listner = iter.next();
          if (!listner.isShowWorldChat()) {
            continue; 
          }
          listner.sendPackets((ServerBasePacket)new S_ServerMessage("奇岩赌场比赛即将开始"));
        } 
        (_gambling = new Gambling()).set_gmaNpc(previous);
        boolean is5m = true;
        int timeS = 300;
        while (is5m) {
          Thread.sleep(1000);
          switch (timeS) {
            case 60:
            case 120:
            case 180:
            case 240:
            case 300:
              npcChat((timeS / 60), 0, null);
              break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
              npcChat(timeS, 1, null);
              break;
            case 1:
              _isStart = true;
              npcChat(0, 2, null);
              break;
            case 0:
              doorOpen(true);
              npcChat(0, 3, null);
              _gambling.startGam();
              is5m = false;
              break;
          } 
          timeS--;
        } 
        _gambling.set_allRate();
        Thread.sleep(2000);
        Iterator<GamblingNpc> iterator = _gambling.get_allNpc().values().iterator();
        while (iterator.hasNext()) {
          GamblingNpc gamblingNpc = iterator.next();
          npcChat(0, 4, gamblingNpc);
          Thread.sleep(1000);
        } 
        while (_gambling.get_oneNpc() == null)
          Thread.sleep(100); 
        
        
        if (_gambling.get_oneNpc() != null) {
          final GamblingNpc one = _gambling.get_oneNpc();
          
          npcChat(0, 5, one);
			final String onename = one.get_npc().getName();
			for (final L1PcInstance listner : World.get().getAllPlayers()) {
				// 拒绝接收广播频道
				if (!listner.isShowWorldChat()) {
					continue;
				}
				listner.sendPackets(new S_ServerMessage(166, "$375(" + _gamblingNo + ")$366 " + onename + " 赔率: "
						+ _gambling.get_oneNpc().get_rate() + " 下注金额: " + one.get_adena()));
			}
			_log.info("奇岩赛狗场:第(" + _gamblingNo + ")场比赛的优胜者是: " + onename + " 赔率: "
					+ _gambling.get_oneNpc().get_rate() + " 下注金额: " + one.get_adena());
          
          final int npcid = _gambling.get_oneNpc().get_npc().getNpcId();
          final double rate = _gambling.get_oneNpc().get_rate();
          final long adena = _gambling.get_allAdena();
          final int outcount = (int)(_gambling.get_oneNpc().get_adena() / 
            GamblingSet.GAMADENA);
          final L1Gambling gambling = new L1Gambling();
          gambling.set_id(_gamblingNo);
          gambling.set_adena(adena);
          gambling.set_rate(rate);
          gambling.set_gamblingno(String.valueOf(String.valueOf(_gamblingNo)) + "-" + npcid);
          gambling.set_outcount(outcount);
          GamblingReading.get().add(gambling);
        } 
        synchronized (this) {
          _gamblingNo++;
        } 
        Thread.sleep(20000);

    } catch (Exception e) {
      _log.error("奇岩赌场时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      GamblingTime timerTask = new GamblingTime();
      timerTask.start();

    } finally {
      if (_gambling == null)
        return; 
      _gambling.delAllNpc();
      _gambling.clear();
      _gambling = null;
      if (!_isStart)
        return; 
      _isStart = false;
    } 
  }
  
  private void doorOpen(boolean isOpen) {
    L1DoorInstance.openGam(isOpen);
  }
  
  private void npcChat(int i, int mode, GamblingNpc gamblingNpc) {
    Collection<L1Object> allObj = World.get().getObject();
    Iterator<L1Object> iterator = allObj.iterator();
    while (iterator.hasNext()) {

      L1Object obj = iterator.next();
      if (!(obj instanceof L1GamInstance))
        continue; 
      L1GamInstance npc = (L1GamInstance)obj;
      switch (mode) {
        case 0:
          if (_random.nextInt(100) < 20) {
          String msg = _msg[_random.nextInt(_msg.length)];
          npc.broadcastPacketX10((ServerBasePacket)new S_NpcChat((L1NpcInstance)npc, msg));
          }
          break;
      } 
    } 
    Iterator<L1Object> iterator2 = allObj.iterator();
    while (iterator2.hasNext()) {
      L1Object obj = iterator2.next();
      if (!(obj instanceof L1GamblingInstance))
        continue; 
      L1GamblingInstance npc = (L1GamblingInstance)obj;
      int npcId = npc.getNpcId();
      switch (mode) {
        case 0:
          if (npcId == 70041)
            npc.broadcastPacketX10((ServerBasePacket)new S_NpcChatShouting((L1NpcInstance)npc, "$376 " + i + "$377")); 
        case 1:
          if (npcId == 70041)
            npc.broadcastPacketX10((ServerBasePacket)new S_NpcChatShouting((L1NpcInstance)npc, String.valueOf(i))); 
        case 2:
          if (npcId == 70041)
            npc.broadcastPacketX10((ServerBasePacket)new S_NpcChatShouting((L1NpcInstance)npc, "$363")); 
        case 3:
          if (npcId == 70041)
            npc.broadcastPacketX10((ServerBasePacket)new S_NpcChatShouting((L1NpcInstance)npc, "$364")); 
        case 4:
          if (npcId == 70041) {
				// $402 的赔率为
        	    GamblingNpc gNpc = gamblingNpc;
        	    if (gNpc == null ) {
        	    	break;
				}
        	    L1NpcInstance npc2 = gNpc.get_npc();
				final String npcname = npc2.getNameId();
				double rate = gamblingNpc.get_rate();
				String si = String.valueOf(rate);

				int re = si.indexOf(".");
				if (re != -1) {
					si = si.substring(0, re + 2);
				}
				String toUser = npcname + " $402 " + si + "$367";

				if (npc != null)
					npc.broadcastPacketAll(new S_NpcChatShouting(npc, toUser));
				break;
          }
		case 5:
			// $375 第 $366 场比赛的优胜者是
			final String onename = gamblingNpc.get_npc().getNameId();
			npc.broadcastPacketX10(new S_NpcChatShouting(npc, "$375 " + _gamblingNo + " $366 " + onename));
			break;
      } 
    } 
  }
}
